import { LogHelper } from "../../utils/logHelper";

class ClaimerFlagTask implements IFlagTask{
  run(flag: Flag): void {
    const roomName = flag.pos.roomName;
    const nearestRoom = this.findNearestRoom(roomName);
    const roomMemory = Game.rooms[nearestRoom].memory;

    // 把需要占领的房间记录在最近的房间里面
    if(!roomMemory.claimers){
      roomMemory.claimers = new Array<string>();
    }
    // 判断其他房间是否有占领记录，如果有则删除掉
    let isClaimerRoom = this.findClaimerRoom(roomName);
    if(isClaimerRoom){
      this.deleteClaimerRoom(roomName,isClaimerRoom);
      LogHelper.info(`删除 房间 [${isClaimerRoom.name}] 对 房间 [${roomName}] 的占领`);
    }
    // 添加记录进内存
    roomMemory.claimers.push(roomName);
    // 修改旗帜命令
    flag.remove();
    flag.name = `占领:${roomName}`;
    flag.setColor(COLOR_YELLOW);
  }

  /**
   * 寻找与指定房间最相近的房间
   */
  private findNearestRoom(roomName: string): string {
    let nearestRoom: string = "";
    let shortestDistance: number | undefined;
    // 遍历所有房间
    for (const room of Object.values(Game.rooms)) {
      if (!room.controller || !room.controller.my) continue;
  
      const route = Game.map.findRoute(roomName, room.name);
      if (route === -2) continue;
  
      const distance = route.length;
      if (shortestDistance === undefined || distance < shortestDistance) {
        shortestDistance = distance;
        nearestRoom = room.name;
      }
    }
    return nearestRoom;
  }

  /**
   * 寻找需要被占领的房间是否被其他房间占领
   */
  private findClaimerRoom(targetName: string): Room | null {
    for(const roomName in Game.rooms){
      const room = Game.rooms[roomName];
      const memory = room.memory;
      if(memory.claimers === undefined){
        continue;
      }
      if(memory.claimers.includes(targetName)){
        return room;
      }
    }
    return null;
  }

  /**
   * 删掉某个房间对目标房间的控制
   */
  private deleteClaimerRoom(targetName: string,room: Room){
    const memory = room.memory;
    const index = memory.claimers.findIndex((element) => {
      return element === targetName;
    });
    if (index !== -1) {
      memory.claimers.splice(index, 1);
    }
  }
}

export {ClaimerFlagTask};